//
// Created by 文道江 on 15/11/19.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "HybridCoreAction.h"
#import "WebViewController.h"


@implementation HybridCoreAction

/**
 * 日志
 */
- (void)logger:(id) log{

    NSDictionary *logInfo = log;

    NSLog(@"[%@] %@", logInfo[@"level"], logInfo[@"args"]);
}

/**
 * 获取设备信息
 */
- (void)getDeviceInfo:(id) data{

    UIDevice *device = [UIDevice currentDevice];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *push_registry_credentials = [KVStorage getValue:@"push_registry_credentials"];
    if (push_registry_credentials == nil)push_registry_credentials = @"";

    self.resultHandler(YES, @{
            @"name": device.name,
            @"systemName": device.systemName,
            @"systemVersion": device.systemVersion,
            @"batteryLevel": @(device.batteryLevel),
            @"batteryState": @(device.batteryState),
            @"batteryMonitoringEnabled": @(device.batteryMonitoringEnabled),
            @"uuid": device.identifierForVendor.UUIDString,
            @"brand": @"Apple",
            @"model": device.model,
            @"localizedModel": device.localizedModel,
            @"orientation": @(device.orientation),
            @"networkState": @([[AFNetworkReachabilityManager sharedManager] networkReachabilityStatus]),
            @"networkStatus": [[AFNetworkReachabilityManager sharedManager] localizedNetworkReachabilityStatusString],
            @"appVersion": infoDictionary[@"CFBundleShortVersionString"],
            @"appVersionCode": infoDictionary[@"CFBundleVersion"],
            @"push_registry_credentials": push_registry_credentials
    });
}

/**
 * 获取网络状态
 */
- (void)getNetworkStatus:(id)params {

    [self callback:YES data:@{
            @"status": @([[AFNetworkReachabilityManager sharedManager] networkReachabilityStatus]),
            @"statusString": [[AFNetworkReachabilityManager sharedManager] localizedNetworkReachabilityStatusString]
    }];
}

/**
 * 设置 显示/隐藏 导航栏
 */
- (void)setNavigationBarHide: (id) params{
    id hide = params[@"hide"];
    if(self.controller.navigationController && hide != nil){
        self.controller.navigationController.navigationBarHidden = [hide boolValue];
    }

    self.resultHandler(self.controller.navigationController != nil, nil);
}

/**
 * 设置主题颜色
 */
- (void)setTheme:(id) params{

    BOOL lightStatusBar = NO;

    if (params[@"lightStatusBar"]){
        lightStatusBar = [params[@"lightStatusBar"] boolValue];
    }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [[UIApplication sharedApplication] setStatusBarStyle:lightStatusBar ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault animated:YES];
#pragma clang diagnostic pop

    if(self.controller.navigationController==nil){
        self.resultHandler(NO, @"The current model does not support setting the theme, because the navigation bar was not found.");
        return;
    }

    NSString *primaryColorString = params[@"primaryColor"];
    NSString *colorString = params[@"color"];

    if([colorString hasPrefix:@"#"]){
        colorString = [colorString substringFromIndex:1];
    }
    if([primaryColorString hasPrefix:@"#"]){
        primaryColorString = [primaryColorString substringFromIndex:1];
    }
    NSLog(@"color: %@, primaryColor: %@, %d", colorString, primaryColorString, lightStatusBar);

    //改变主题
    //self.controller.navigationController.navigationBarHidden = !self.controller.navigationController.navigationBarHidden;

    UIColor *primaryColor = [MAThemeKit colorWithHexString:primaryColorString];
    UIColor *color = [MAThemeKit colorWithHexString:colorString];
    [MAThemeKit setupThemeWithPrimaryColor:primaryColor secondaryColor:color fontName:nil lightStatusBar:lightStatusBar];

    self.resultHandler(YES, @"success");

    [[HybridBridge defaultHybridBridge] setTheme:[AppTheme themeWithPrimaryColor:primaryColor color:color lightStatusBar:lightStatusBar]];

}

/**
 * 打开一个新的 webview 窗口
 */
- (void)openWindow:(id)params {

    if (params[@"url"] == nil){
        [self callback:NO data:@"url error!"];
        return;
    }
    WebViewController *webViewController = [[WebViewController alloc] init];
    [webViewController setOpenUrl:params[@"url"]];
    if (self.controller.navigationController){
        [self.controller.navigationController pushViewController:webViewController animated:YES];
    }else{
        [self.controller presentViewController:webViewController animated:YES completion:nil];
    }
}

- (void)closeWindow:(id)params{

    if (self.controller.navigationController != nil){
        [self.controller.navigationController popViewControllerAnimated:YES];
    }else{
        [self.controller dismissViewControllerAnimated:YES completion:nil];
    }
}

/**
 * 打开一个URL
 */
- (void)openURL:(id)params {
    if (params[@"url"] == nil){
        [self callback:NO data:@"url error!"];
        return;
    }
    NSURL *url = [NSURL URLWithString:params[@"url"]];
    if (url == nil){
        [self callback:NO data:@"url parse error!"];
        return;
    }
    if([[UIApplication sharedApplication] canOpenURL: url]){
        [[UIApplication sharedApplication] openURL:url];
        [self callback:YES data:@"success"];
    }else{
        [self callback:NO data:@"fail"];
    }
    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //[self.webView loadRequest:request];
}

/**
 * 播放震动
 */
- (void)playVibrate:(id)params {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

/**
 * 播放声音
 */
- (void)playSound:(id)params {
    if (params[@"url"] == nil){
        [self callback:NO data:@"url params not found."];
        return;
    }
    SystemSoundID soundIDTest = 0;
    NSString *path = [[NSBundle mainBundle] pathForResource:params[@"url"] ofType:@""];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
        [self callback:NO data:@"file not found."];
        return ;
    }

    AudioServicesCreateSystemSoundID( (__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundIDTest );

    if (soundIDTest > 0){
        AudioServicesPlaySystemSound( soundIDTest );
        //AudioServicesDisposeSystemSoundID( soundIDTest );
        [self callback:YES data:path];
    }else{
        [self callback:NO data:@"play fail"];
    }
}

/**
 * 设置 app 图标上的数字
 */
- (void)setIconBadge:(id)params{
    if (params[@"badge"]){
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber: [params[@"badge"] integerValue]];
        [self callback:YES data:nil];
    }else{
        [self callback:NO data:@"params 'badge' not found."];
    }
}

- (void)setValue:(id)params {
    NSString *key = params[@"key"];
    if (key == nil || key.length == 0){
        [self callback:NO data:@"key 不能为空"];
        return;
    }
    [KVStorage setKey:key Value:params[@"value"]];
    [self callback:YES data:@"success"];
}

- (void)getValue:(id)params {
    NSString *key = params[@"key"];
    if (key == nil || key.length == 0){
        [self callback:NO data:@"key 不能为空"];
        return;
    }
    id value = [KVStorage getValue:key];
    if (value){
        [self callback:YES data:value];
    }else{
        [self callback:NO data:[NSNull null]];
    }
}

/**
 * 获取个推cid
 */
- (void)getGeTuiClientId:(id)params {
    NSString *GeTuiClientId = [KVStorage getValue:@"GeTuiClientId"];
    if (GeTuiClientId != nil && GeTuiClientId.length > 0){
        [self callback:YES data:GeTuiClientId];
    }else{
        [self callback:NO data:@"获取错误"];
    }
}

/*
 * 推送开关
 * */
- (void)setPushSwitch:(id)params {
    id pushOff = params[@"pushOn"];
    BOOL isPushOff = NO;
    if (pushOff != nil){
        isPushOff = [pushOff boolValue];
    }
    [[HybridEventBus defaultEventBus] postData:@{
            @"pushOff": @(isPushOff)
    } Tag:@"setPushSwitch"];
}

/**
 * 设置kv数据
 * @param params
 */
- (void)setKVStoreValue:(id)params {
    NSString *key = params[@"name"];
    NSString *value = params[@"value"];

    if (key != nil && value != nil) {
        [KVStorage setKey:key Value:value];
        [self callback:YES data:value];
    } else {
        [self callback:NO data:@"params error."];
    }
}

/**
 * 获取kv数据
 * @param params
 */
- (void)getKVStoreValue:(id)params {
    NSString *key = params[@"name"];
    if (key != nil) {
        id value = [KVStorage getValue:key];
        if (value != nil){
            [self callback:YES data:value];
            return;
        }
    }
    [self callback:NO data:@"not found data!"];
}

/**
 * AJAX 功能
 */
- (void)ajax:(id)params{

    NSString *type = params[@"type"] == nil ? @"get" : params[@"type"];
    NSString *dataType = params[@"dataType"] == nil ? @"json" : params[@"dataType"];
    NSString *url = params[@"url"];
    NSString *ajaxTag = [NSString stringWithFormat:@"%lf_%d", [NSDate timeIntervalSinceReferenceDate], url.hash];
    NSDictionary *data = params[@"data"] == nil ? @{} : params[@"data"];

    if (!url || ![url hasPrefix:@"http"]){
        [self callback:NO data:@"Wrong url!"];
        return;
    }

    [self callback:YES data:ajaxTag];

    NSURLSessionTask *sessionTask = [URLSessionManager ajax:type
                        url:[NSURL URLWithString:url]
                   dataType:dataType
                     params:data
                 completion:^(NSURLResponse *response, id responseObject, NSError *error) {
                     NSLog(@"ajax:complete");
                     [self dispatchEvent:@"ajax:complete" data:ajaxTag];
                     int statusCode = 0;
                     if ([response isKindOfClass:[NSHTTPURLResponse class]]){
                         NSHTTPURLResponse *httpUrlResponse = (NSHTTPURLResponse *) response;
                         statusCode = httpUrlResponse.statusCode;
                     }

                     id result;
                     if ([dataType.lowercaseString isEqualToString:@"json"]){
                         id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                         if (error == nil)result = json;
                     } else{
                         result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                     }

                     if (error == nil) {
                         [self dispatchEvent:@"ajax:success" data:@{
                                 @"statusCode": @(statusCode),
                                 @"data": result,
                                 @"tag": ajaxTag
                         }];
                     } else {
                         [self dispatchEvent:@"ajax:error" data:@{
                                 @"statusCode" : @(statusCode),
                                 @"error" : error.localizedDescription,
                                 @"data" : result,
                                 @"tag" : ajaxTag
                         }];
                     }
                 }
    ];
    [sessionTask resume];
    [self dispatchEvent:@"ajax:beforeSend" data:ajaxTag];
}

@end